package com.yichat.micro.msghttpservice.core.metrics;

import com.yichat.micro.msghttpservice.core.base.AbstractHttpCaller;
import com.yichat.micro.msghttpservice.core.base.AdvancedExecutor;
import lombok.Setter;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.concurrent.atomic.LongAdder;

/**
 * @功能:
 * @作者:chanson
 * @时间:2019/4/22 22:50
 */
@Component
public class RequestExecutorMonitor {

    private LongAdder totalRequest = new LongAdder();

    @Setter
    private long appStartTime;

    public void addRequestNumber() {
        totalRequest.increment();
    }

    /**
     * 返回队列可使用数量
     *
     * @return
     */
    public int getQueueRemainNumber() {
        return AbstractHttpCaller.getRequestExecutor().getQueue().remainingCapacity();
    }

    /**
     * 返回当前活跃线程数量
     *
     * @return
     */
    public int countActiveThread() {
        return ((AdvancedExecutor) AbstractHttpCaller.getRequestExecutor()).getActiveThreadNumber().intValue();
    }

    /**
     * 粗略计算tps
     *
     * @return
     */
    public double tps() {
        long duration = (new Date().getTime() - appStartTime) / 1000;
        double tps = totalRequest.doubleValue() / duration;
        return tps;
    }
}
